#!/usr/bin/env ts-node

import { StockDataCrawler } from '../services/StockDataCrawler';

async function main() {
  console.log('🚀 开始批量导入A股股票数据...');
  
  const crawler = new StockDataCrawler({
    batchSize: 200, // 进一步加大批次大小提高效率
    delayBetweenBatches: 800 // 减少延迟
  });

  try {
    // 导入所有A股数据
    await crawler.importAllAStocks();
    console.log('✅ 股票数据导入完成!');
    
    // 显示统计信息
    const { PrismaClient } = await import('@prisma/client');
    const prisma = new PrismaClient();
    
    const totalStocks = await prisma.stock.count();
    const marketStats = await prisma.stock.groupBy({
      by: ['marketId'],
      _count: {
        _all: true
      }
    });
    
    console.log(`\n📊 导入统计:`);
    console.log(`总股票数: ${totalStocks}`);
    
    // 获取市场信息并显示统计
    const markets = await prisma.market.findMany();
    const marketMap = new Map(markets.map(m => [m.id, m]));
    
    for (const stat of marketStats) {
      const market = marketMap.get(stat.marketId);
      console.log(`${market?.marketName || '未知市场'}: ${stat._count._all} 只`);
    }
    
    await prisma.$disconnect();
  } catch (error) {
    console.error('❌ 导入失败:', error);
    process.exit(1);
  }
  
  console.log('🎉 程序执行完成');
  process.exit(0);
}

// 运行主函数
main().catch(console.error);